package vincent.com.layouttest.util;

import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;

import java.util.HashMap;

/**
 * Created by chenzhengwen on 2015/12/11.
 */
public class PreferenceUtil {
    private static final String PREFERENCE_FILE = "pref_file";
    private static final HashMap<String, String> mPreferenceFileMap = new HashMap<String, String>();

    static {
        mPreferenceFileMap.put(Const.MY_PREFERENCE_FIELD, PREFERENCE_FILE);
    }

    public static void setStringField(Context context, String key, String value){
        setStringField(context, key, value, Context.MODE_PRIVATE);
    }

    public static void setStringField(Context context, String key, String value, int mode){
        if(TextUtils.isEmpty(key)){
            throw new  IllegalArgumentException("the key should not be null or empty!");
        }
        String prefFileName = mPreferenceFileMap.get(key);

        if(prefFileName != null && !"".equals(prefFileName)){
            SharedPreferences preferences = context.getSharedPreferences(prefFileName, mode);
            preferences.edit().putString(key, value).commit();
        }
    }

    public static String getStringField(Context context, String key, int mode){
        if(TextUtils.isEmpty(key)){
            throw new  IllegalArgumentException("the key should not be null or empty!");
        }

        String prefFileName = mPreferenceFileMap.get(key);

        if(prefFileName != null && !"".equals(prefFileName)){
            SharedPreferences preferences = context.getSharedPreferences(prefFileName, Context.MODE_PRIVATE);
            return preferences.getString(key, "");
        }

        return null;
    }

    public static String getStringField(Context context, String key){
        return getStringField(context, key, Context.MODE_PRIVATE);
    }

}
